import { createStore } from 'vuex'
import user from './modules/user'
import board from './modules/board'
import config from './modules/config'
import message from './modules/message'
import article from './modules/article'
import api from '@/api/index'

export default createStore({
  state: {
    boards: [],
    articles: {
      list: [],
      loading: false,
      total: 0,
      page: 1,
      size: 10
    },
    messages: {
      list: [],
      unreadCount: 0,
      loading: false
    }
  },
  mutations: {
    // 板块相关
    setBoards(state, boards) {
      state.boards = boards
    },
    
    // 文章相关
    setArticles(state, payload) {
      state.articles.list = payload.list
      state.articles.total = payload.total
      state.articles.page = payload.page
      state.articles.size = payload.size
    },
    setArticlesLoading(state, loading) {
      state.articles.loading = loading
    },
    
    // 消息相关
    setMessages(state, messages) {
      state.messages.list = messages
    },
    setUnreadCount(state, count) {
      state.messages.unreadCount = count
    },
    setMessagesLoading(state, loading) {
      state.messages.loading = loading
    }
  },
  actions: {
    // 全局初始化 - 获取站点配置
    fetchSiteConfig({ dispatch }) {
      return dispatch('config/fetchSiteConfig')
    },
    
    // 全局初始化 - 获取所有板块
    fetchAllBoards({ dispatch }) {
      return dispatch('board/getAllBoards')
    },
    
    // 板块相关
    async fetchBoards({ commit }) {
      try {
        const res = await api.board.getTopBoards()
        if (res.code === 0) {
          commit('setBoards', res.data || [])
          return res.data || []
        }
        return []
      } catch (error) {
        console.error('获取板块失败', error)
        return []
      }
    },
    
    // 文章相关
    async fetchArticles({ commit }, { boardId, page = 1, size = 10, sort = '' }) {
      commit('setArticlesLoading', true)
      try {
        // 构建API参数，确保将排序参数传递给后端
        const params = {
          page,
          size
        };
        
        // 如果有板块ID，添加到参数中
        if (boardId) {
          params.boardId = boardId;
        }
        
        // 处理排序参数
        if (sort) {
          // 将前端的排序参数映射到后端需要的格式
          switch(sort) {
            case 'hot':
              params.sort = 'hot'; // 热门文章，按访问量排序
              break;
            case 'new':
              params.sort = 'new'; // 最新文章，按创建时间排序
              break;
            case 'comment':
              params.sort = 'comment'; // 按评论数排序
              break;
            default:
              params.sort = 'new'; // 默认按创建时间排序
          }
        }
        
        // 调用API获取数据，传递完整参数
        const res = await api.article.getList(params);
        
        if (res.code === 0) {
          const articleList = res.data || [];
          const total = res.total || articleList.length;
          
          commit('setArticles', {
            list: articleList,
            total: total,
            page,
            size
          });
          
          return articleList;
        }
        return [];
      } catch (error) {
        console.error('获取文章列表失败', error);
        return [];
      } finally {
        commit('setArticlesLoading', false);
      }
    },
    
    // 消息相关
    async fetchMessages({ commit }) {
      commit('setMessagesLoading', true)
      try {
        const res = await api.message.getList()
        if (res.code === 0) {
          commit('setMessages', res.data || [])
          // 计算未读消息数量
          const unreadCount = (res.data || []).filter(msg => msg.status === 0).length
          commit('setUnreadCount', unreadCount)
        }
      } catch (error) {
        console.error('获取消息列表失败', error)
      } finally {
        commit('setMessagesLoading', false)
      }
    }
  },
  getters: {
    boardMap: state => {
      const map = {}
      state.boards.forEach(board => {
        map[board.id] = board
      })
      return map
    },
    userArticleCount: (_, getters) => {
      const userInfo = getters['user/userInfo'] || {}
      return userInfo.articleCount || 0
    },
    userCommentCount: (_, getters) => {
      const userInfo = getters['user/userInfo'] || {}
      return userInfo.commentCount || 0
    },
    userLikeCount: (_, getters) => {
      const userInfo = getters['user/userInfo'] || {}
      return userInfo.likeCount || 0
    }
  },
  modules: {
    user,
    board,
    config,
    message,
    article
  }
}) 